package com.bit.webhttp.V3;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class HttpServerV3 {
    static class User{
        //保存用户信息
        public String userName;
        public int age;
        public String school;
    }
    private ServerSocket serverSocket = null;
    //session会话，指的就是同一个用户的一组访问服务器的操作，归类到一起就是一个会话
    private Map<String,User> sessions = new HashMap<>();


    public HttpServerV3(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动");
        ExecutorService executorService = Executors.newCachedThreadPool();
        while(true){
            Socket clientSocket = serverSocket.accept();
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    process(clientSocket);
                }
            });
        }
    }
    public void process(Socket clientSocket){

        try {
            //1.读取请求并解析
            HttpRequest request = HttpRequest.build(clientSocket.getInputStream());
            System.out.println("request:"+request);
            HttpResponse response = HttpResponse.build(clientSocket.getOutputStream());
            //2.根据请求计算响应
            if("GET".equalsIgnoreCase(request.getMethod())){
                doGet(request,response);
            }else if("POST".equalsIgnoreCase(request.getMethod())){
                doPost(request,response);
            }else{
                response.setStatue(405);
                response.setMessage("Method Not Allowed");
            }
            response.flush();
        } catch (IOException | NullPointerException e) {
            e.printStackTrace();
        }finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    private void doGet(HttpRequest request,HttpResponse response) throws IOException {
        //1.能支持返回一个html文件
        if(request.getUrl().startsWith("/index.html")){
            String sessionId = request.getCookie("sessionId");
            User user = sessions.get(sessionId);
            if(sessionId == null || user == null){
                //说明当前用户尚未登录，返回一个登陆界面
                response.setStatue(200);
                response.setMessage("OK");
                response.setHeader("Content-Type","text/html;charset=utf-8");
                InputStream inputStream = HttpServerV3.class.getClassLoader().getResourceAsStream("index.html");
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                //按行读取内容，把数据写入到response中
                String line = "";
                while ((line = bufferedReader.readLine()) != null){
                    response.writeBody(line+ "\n");
                }
                bufferedReader.close();
            }else{
                //用户已经登陆，无需再登陆
                response.setStatue(200);
                response.setMessage("OK");
                response.setHeader("Content-Type","text/html;charset=utf-8");
                response.writeBody("<html>");
                response.writeBody("<div>"+"您已经登陆了"+user.userName+"</div>");
                response.writeBody(+user.age+"</div>");
                response.writeBody("<div>"+user.school+"<div>");
                response.writeBody("</html>");
            }
        }
    }
    public void doPost(HttpRequest request,HttpResponse response){
        //2.实现/login的处理
        if (request.getUrl().startsWith("/login")){
            //读取用户提交的用户名和密码
            String userName = request.getParameter("username");
            String passWord = request.getParameter("password");
            if("yx".equals(userName)&&"123".equals(passWord)){
                //登陆成功
                response.setStatue(200);
                response.setMessage("OK");
                response.setHeader("Content-Type","text/html;charset=utf-8");
                //给浏览器返回一个随机的sessionId，保证安全性
                String sessionId = UUID.randomUUID().toString();
                User user = new User();
                user.userName = "yx";
                user.age = 21;
                user.school = "河南大学";
                sessions.put(sessionId,user);
                response.setHeader("Set-Cooike","sessionId="+sessionId);
                response.writeBody("<html>");
                response.writeBody("<div>欢迎你！"+userName+"</div>");
                response.writeBody("</html>");
            }else{
                //登陆失败
                response.setStatue(403);
                response.setMessage("Forbidden");
                response.setHeader("Content-Type", "text/html; charset=utf-8");
                response.writeBody("<html>");
                response.writeBody("<div>登陆失败</div>");
                response.writeBody("</html>");
            }
        }
    }

    public static void main(String[] args) throws IOException {
        HttpServerV3 serverV3 = new HttpServerV3(9090);
        serverV3.start();
    }
}
